package actions;

/*
 * Name: Minh-Tuan ta
 * Class: Action.java
 */

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public abstract class Action {
	protected String urlMapping;
	
	protected abstract void setURLMapping();
	
	public String getURLMapping()
	{
		return urlMapping;
	}
	
	public Action()
	{
		setURLMapping();
	}
	
	protected void setContent(HttpServletRequest request, String url)
	{
		if (url != null)
		{
			if (request.getMethod().equals("GET")) //if the request is a GET request
			{
				//set the content attribute
				request.setAttribute("content", url);
			}
			else //if the request is a POST request
			{
				//set the url attribute
				request.setAttribute("url", url);
			}
		}
		else
		{
			//if the request is a GET request
			if (request.getMethod().equals("GET"))
			{
				//set the content attribute
				request.setAttribute("content", "/WEB-INF/views/content/PageNotFound.jsp");
			}
			else //if it is a POST request
			{
				//set the url attribute
				request.setAttribute("content", "PageNotFound");
			}
		}
	}
	
	public void perform(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String url = null;
		
		setupPage(request, response);
		
		if (request.getMethod().equals("GET"))
		{
			url = doGet(request, response);
		}
		else
		{
			url = doPost(request, response);
		}
		
		setContent(request, url);
	}
	
	protected abstract void setupPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
	
	protected String getLastURL(HttpServletRequest request, HttpSession session)
	{
		String url = "Home";
		
		if (session.getAttribute("LastURL") != null)
		{
			url = (String)session.getAttribute("LastURL");
			session.removeAttribute("LastURL");
		}
		
		return url;
	}
	
	protected abstract String doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
	protected abstract String doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
